package com.hw.common.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Md5Util {

	/**
	 * 获取md5生成后的串，16进制处理
	 * @param str
	 * @return
	 * @throws NoSuchAlgorithmException
	 */
	public static String getMd5(String str) throws NoSuchAlgorithmException{
		MessageDigest md = MessageDigest.getInstance("MD5");
		md.update(str.getBytes());
		byte[] encodedPassword = md.digest();

		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < encodedPassword.length; i++) {
			if ((encodedPassword[i] & 0xff) < 0x10) {
				sb.append("0");
			}
			sb.append(Long.toString(encodedPassword[i] & 0xff, 16));
		}
		return sb.toString();
	}
	
	public static boolean volidMd5(String str, String strMd5) throws NoSuchAlgorithmException{
		if(str!=null){
			str = getMd5(str);
			System.out.println(str);
			return str.equals(strMd5);
		}
		return false;
	}
	
	public synchronized static final byte[] toMd5(String data) {
		byte[] sss = null;
		 try{
			 MessageDigest md = MessageDigest.getInstance("MD5");
	
			    sss = md.digest(data.getBytes());
	
			} catch (Exception e) {
	
			    throw new RuntimeException(e);
	
			}
		 return sss;
	}

	public final static String MD5Encoder(String s, String charset) {         
		try {             
			byte[] btInput = s.getBytes(charset);             
			MessageDigest mdInst = MessageDigest.getInstance("MD5");             
			mdInst.update(btInput);             
			byte[] md = mdInst.digest();             
			StringBuffer sb = new StringBuffer();             
			for (int i = 0; i < md.length; i++) {                 
				int val = ((int) md[i]) & 0xff;                 
				if (val < 16){                     
					sb.append("0");                 
					}                 
				sb.append(Integer.toHexString(val));             
				}             
			return sb.toString();         
		} catch (Exception e) {             
			return null;         
		}     
	}
}
